<?php
/**
 * Created by PhpStorm.
 * User: xiaofang
 * Date: 2020/12/12
 * Time: 12:40
 */

namespace app\admin\model;


use think\Db;
use think\Exception;
use think\Model;

class NydDev extends Model
{
    public function devStatus($gateway_id)
    {
        if(cache("dev".$gateway_id)){
            return cache("dev".$gateway_id);
        }

        $agw = new Agateway();
        $gw_id = $agw->gw_id($gateway_id);

        //设备列表
        $nycontrol = new NydControlDev();
        $dev_list = $nycontrol->getDevList($gw_id);

        //设备状态
        $devStatus = [];
        foreach ($dev_list as $k => $v)
        {
            $devStatus[$v['control_id']] = $v['is_open'];
        }
        $this->setDevStatus("dev".$gateway_id,$devStatus);
        return $devStatus;
    }

    /**
     * 设置设备状态
     */
    public function setDevStatus($key,$devStatus)
    {
        cache($key,$devStatus);
        return true;
    }

    /**
     * 设备下线
     */
    public function offline()
    {
        $db_dev = Db::name("ny_dev");
        try{
            $db_dev->where("is_del",'1')
                ->update([
                    'is_open'   =>  '0',
                ]);
        }catch (Exception $exception){
            return json(ret_com(0,
                'error '.$exception->getMessage()
            ));
        }
    }

    /**
     * 临时数据
     */
    public function ls_time($input_time)
    {
        $ls_time = \cache("ls_time");
        if(!$ls_time){
            $ls_time = $input_time;
            \cache('ls_time',$ls_time);
        }
        return $ls_time;
    }

    /**
     * 获取设备列表
     */
    public function get_devlist()
    {
        $tb_control = Db::name("nyd_control_dev");

        $select_str = "a.id,b.gateway_id,a.gateway_id as wangguan_id,a.is_open,
        a.is_bad,a.control_shortname,a.control_id,a.open_imgUrl,a.close_imgUrl ";

        return $tb_control->alias("a")
            ->join("nyd_gateway b","a.gateway_id = b.id")
            ->where("a.is_del",1)
            ->field($select_str)
            ->select();
    }
}